import { Component, EventTouch, Node, _decorator } from 'cc';
import { Vec2 } from '../../game/lib/kgame/d2/math/Vec2';
import { Conn } from '../conn/Conn';
const { ccclass, property } = _decorator;

@ccclass('UIRocker')
export class UIRocker extends Component {

    ctrlSet = new Set<number>();
    rot: number = 0;
    /** 摇杆上的点 */
    pointNode!: Node;
    /** 摇杆点移动范围 */
    pointRange = 32;

    start() {
        this.pointNode = this.node.children[0];

        this.node.on(Node.EventType.TOUCH_START, this.onCtrl, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onCtrl, this);
        this.node.on(Node.EventType.TOUCH_END, this.onDone, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onDone, this);
    }

    /** 控制摇杆 */
    onCtrl(e: EventTouch) {

        this.ctrlSet.add(1);
        let pos = e.getUILocation();
        let dis = Vec2.dis(this.node.worldPosition, pos);
        //超出的部分
        let extra = dis - this.pointRange;
        if (extra > 0) {
            Vec2.moveTo(pos, this.node.worldPosition, extra);
        }
        this.pointNode.setWorldPosition(pos.x, pos.y, 0);

        const rad = Vec2.radTo(Vec2.ZERO, this.pointNode.position);
        Conn.send(KProtoId.ctrlRot, { rot: rad })
    }

    /** 结束控制 */
    onDone() {
        this.ctrlSet.delete(1);
        this.pointNode.setPosition(0, 0);
    }


    update(dt: number) {
    }
}
